<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 查询框 -->
      <el-input
        v-model="listQuery.name"
        :placeholder="$t('table.title')"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <!-- 下拉框查询 -->
          <el-select
            v-model="listQuery.CommodityTypeId"
            placeholder="请选择商品类别"
            clearable
            :style="{ width: '180px' }"
          >
            <el-option
              v-for="(item, index) in CommodTypeIdOptions"
              :key="index"
              :label="item.commodTypeName"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
      <!-- 搜索 -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t("table.search") }}
      </el-button>
      <!-- 添加 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t("table.add") }}
      </el-button>
      <!-- 导出 -->
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        {{ $t("table.export") }}
      </el-button>
       <!-- 跳转 -->
       <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        @click="$router.push('/book/show')"
      >
       回收站
      </el-button>
    </div>
    <!-- 显示 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        :label="$t('table.id')"
        prop="id"
        sortable="custom"
        align="center"
        width="150"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.commodityName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.date')" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>￥{{ row.commoditySalePrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.commoditySaleBegin }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" min-width="100px">
        <template slot-scope="{ row }">
          <span>{{ row.commodityState === 1 ? "上架" : "下架" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品详情" width="250px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.commodityDetails }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="380"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t("table.edit") }}
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ $t("table.delete") }}
          </el-button>
          <el-button size="mini" type="danger" @click="deletes(row, $index)">
            永久删除
          </el-button>
           <el-button size="mini" type="primary" @click="upfile(row, $index)">
            上传图片
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 上传图片 -->
    <el-dialog :visible.sync="isupload" title="上传图片">
      <el-form :model="load" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="上传" prop="" required>
          <el-upload
            ref="PhotoUrl"
            :file-list="field101fileList"
            :action="field101Action"
            :before-upload="field101BeforeUpload"
            :on-success="successload"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="createload">提交</el-button>

          <el-button type="primary" @click="jhss">666</el-button>

        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :page-sizes="[2,4,6,8]"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 添加模态框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="商品名称" prop="commodityName">
          <el-input
            v-model="temp.commodityName"
            placeholder="请输入商品名称"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商品副标题" prop="commoditySubtitle">
          <el-input
            v-model="temp.commoditySubtitle"
            placeholder="请输入商品副标题"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="commodityDisplay">
          <el-radio-group v-model="temp.commodityDisplay" size="medium">
            <el-radio
              v-for="(item, index) in field103Options"
              :key="index"
              :label="item.value"
              :disabled="item.disabled"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="销售开始时间" prop="commoditySaleBegin">
          <el-date-picker
            v-model="temp.commoditySaleBegin"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :style="{ width: '100%' }"
            placeholder="请选择销售开始时间"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="销售价格" prop="commoditySalePrice">
          <el-input
            v-model="temp.commoditySalePrice"
            placeholder="请输入销售价格"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="促销价格" prop="commodiSPromotion">
          <el-input
            v-model="temp.commodiSPromotion"
            placeholder="请输入促销价格"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商品详情" prop="commodityDetails">
          <el-input
            v-model="temp.commodityDetails"
            placeholder="请输入商品详情"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="重量" prop="commodityWeight">
          <el-input
            v-model="temp.commodityWeight"
            placeholder="请输入重量"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="是否包邮" prop="commodityFreight">
          <el-radio-group v-model="temp.commodityFreight" size="medium">
            <el-radio
              v-for="(item, index) in field109Options"
              :key="index"
              :label="item.value"
              :disabled="item.disabled"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品条形码" prop="commodityBarCode">
          <el-input
            v-model="temp.commodityBarCode"
            placeholder="请输入商品条形码"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商品详情描述" prop="commodityDescription">
          <el-input
            v-model="temp.commodityDescription"
            placeholder="请输入商品详情描述"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="commodityState">
          <el-radio-group v-model="temp.commodityState" size="medium">
            <el-radio
              v-for="(item, index) in field112Options"
              :key="index"
              :label="item.value"
              :disabled="item.disabled"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="浏览量" prop="CommodityBorwseNum">
          <el-input
            v-model="temp.commodityBorwseNum"
            placeholder="请输入浏览量"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="销售量" prop="CommoditySaleNum">
          <el-input
            v-model="temp.commoditySaleNum"
            placeholder="请输入销售量"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="评价数" prop="CommodityEvaluaNum">
          <el-input
            v-model="temp.commodityEvaluaNum"
            placeholder="请输入评价数"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商品属性" prop="CommodityAttrName">
          <el-input
            v-model="temp.commodityAttrName"
            placeholder="请输入商品属性"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="商品类别" prop="CommodTypeId">
          <el-select
            v-model="temp.commodTypeId"
            placeholder="请选择商品类别"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in CommodTypeIdOptions"
              :key="index"
              :label="item.commodTypeName"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 反填修改模态款 -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{
          $t("table.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from "@/api/book";
import waves from "@/directive/waves";
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination";

const calendarTypeOptions = [];

const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      field103Options: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 2,
        },
      ],
      field109Options: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 2,
        },
      ],
      field112Options: [
        {
          label: "上架",
          value: 1,
        },
        {
          label: "下架",
          value: 2,
        },
      ],
      listQuery: {
        page: 1,
        limit: 2,
        skipCount: 1,
        maxResultCount: 2,
        importance: undefined,
        title: undefined,
        name: undefined,
        type: undefined,
        sort: "+id",
        id:1,
        commodityDisplay:1,
        CommodityTypeId:undefined
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
        commodityDisplay:2,
      },
      load: {
        PhotoUrl: null,
        ForeignKeyId: undefined,
        TypeId: undefined,
        imglist:[]
      },
      i:0,
      isupload:false,
      field101Action:
        "https://localhost:44325/api/app/commodity-info-my-self/upload",
      field101fileList: [],
      CommodTypeIdOptions: [],
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.selectoption();
  },
  methods: {
    getList() {
      this.listLoading = true;
      this.listQuery.skipCount =
        (this.listQuery.page - 1) * this.listQuery.limit;
      this.listQuery.maxResultCount=this.listQuery.limit;
      fetchList(this.listQuery).then((response) => {
        console.log(response);
        this.list = response.items;
        this.total = response.totalCount;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 0.1 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success",
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
      this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
          this.temp.author = "vue-element-admin";
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex((v) => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      row.commodityDisplay=2;
       this.axios.put("https://localhost:44325/api/app/commodity-info/"+row.id,row)
            .then()
            {
                this.$notify({
                title: "成功",
                message: "回收成功",
                type: "success",
                duration: 2000,
            });
            this.list.splice(index, 1);
            }
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status",
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list",
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
    deletes(row, index) {
      if (confirm("你确定删除吗？")) {
        this.axios
          .delete("https://localhost:44325/api/app/commodity-info/" + row.id)
          .then(() => {
            alert("删除成功!");
            this.list.splice(index, 1);
          });
      }
    },
    selectoption() {
      this.axios
        .get("https://localhost:44325/api/app/commodity-type")
        .then((response) => {
          this.CommodTypeIdOptions = response.data.items;
        });
    },
    upfile(row) {
      this.load.ForeignKeyId = row.id;
      this.isupload = true;
    },
    field101BeforeUpload(file) {
       let isRightSize = file.size / 1024 / 1024 < 2;
       if (!isRightSize) {
         this.$message.error("文件大小超过 2MB");
       }
       return isRightSize;
     },
    successload(r,file) {
      
    
        this.load.PhotoUrl = file.response;
     
        this.load.imglist.push(this.load.PhotoUrl);
        console.log(this.load.imglist)
       
      
      
       
    },
    createload(){
      this.axios
        .post(
          "https://localhost:44325/api/app/commodity-info-my-self/img/",
          this.load
        )
        .then(() => {
          this.$notify({
            title: "成功",
            message: "上传成功",
            type: "success",
            duration: 2000,
          });
          this.isupload = false;
          this.load.imglist=[];
        });
    },
    jhss()
    {
      alert(this.load.imglist)
    }
  },
};
</script>
